import request from "@/utils/request";
import API from "@/api";
import { setToken, removeAllToken } from "@/utils/auth.ts";

const title = import.meta.env.VITE_GLOB_APP_TITLE;
const token = import.meta.env.VITE_GLOB_TOKEN_KEY;

const useUserStore = defineStore("userStore", {
  state: () => ({
    userInfo: "",
  }),

  getters: {
    getUserInfo(state): Record<string, any> {
      return JSON.parse(state.userInfo);
    },
  },

  actions: {
    setUserInfo(userInfo: object) {
      this.userInfo = JSON.stringify(userInfo);
    },

    // 登录
    async login(loginForm: object): Promise<boolean> {
      const res = await request.post(API.login, loginForm);
      const accessToken: string = "中华人民共和国万岁";
      if (accessToken) {
        const expirationTime = new Date();
        expirationTime.setMonth(expirationTime.getMonth() + 1);
        setToken(token, accessToken, { expires: expirationTime });
      }
      if (res.code === 1) {
        this.setUserInfo(res.data);
        const hour: number = new Date().getHours();
        let thisTime: string = "早上好";
        switch (true) {
          case hour < 8:
            thisTime = "早上好";
            break;
          case hour <= 11:
            thisTime = "上午好";
            break;
          case hour <= 13:
            thisTime = "中午好";
            break;
          case hour < 18:
            thisTime = "下午好";
            break;
          default:
            thisTime = "晚上好";
        }
        ElNotification({
          title: `欢迎登录${title}`,
          message: thisTime,
          type: "success",
        });
        return true;
      }
      return false;
    },
    // 退出登录
    async logout() {
      const res = await request.post(API.logout);
      if (res.code === 1) {
        this.closeAll();
      }
    },

    closeAll() {
      removeAllToken();
      sessionStorage.clear();
      localStorage.clear();
      location.reload();
    },
  },
  persist: {
    key: "useUserStore", //存储名称
    storage: sessionStorage, // 存储方式
    paths: ["userInfo"],
  },
});

export default useUserStore;
